const api = require('../../utils/api.js');

Page({
  data: {
    avatarUrl: '',
    nickname: '',
    showPwdModal: false,
    password: '',
    confirmPassword: '',
    pwdLoading: false
  },

  onShow() {
    this.loadProfile();
  },

  // 加载用户资料
  async loadProfile() {
    try {
      wx.showLoading({ title: '加载中...' });
      const res = await api.getUserInfo();
      wx.hideLoading();
      if (res.code === 200) {
        const profileData = res.data;
        this.setData({
          avatarUrl: profileData.avatar_url || api.getDefaultUserAvatar(),
          nickname: profileData.nickname || '未设置昵称'
        });
      } else {
        this.setData({
          avatarUrl: api.getDefaultUserAvatar(),
          nickname: '未设置昵称'
        });
        wx.showToast({
          title: res.msg || '获取用户信息失败',
          icon: 'none'
        });
      }
    } catch (e) {
      wx.hideLoading();
      this.setData({
        avatarUrl: api.getDefaultUserAvatar(),
        nickname: '未设置昵称'
      });
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    }
  },

  // 跳转到资料编辑页
  goEditProfile() {
    wx.navigateTo({
      url: '/pages/edit_profile/edit_profile'
    });
  },

  // 跳转到对话历史
  goChatHistory() {
    wx.navigateTo({
      url: '/pages/history/history'
    });
  },

  // 跳转到测评历史
  goTestHistory() {
    wx.navigateTo({
      url: '/pages/test_history/test_history'
    });
  },

  // 会员中心
  goVip() {
    wx.navigateTo({
      url: '/pages/index/index'
    });
  },

  // 联系开发者
  contactDev() {
    wx.showModal({
      title: '联系开发者',
      content: '邮箱：dev@example.com\n微信：dev_wechat',
      showCancel: false
    });
  },

  // 打开账户密码弹窗
  goSetPassword() {
    this.setData({
      showPwdModal: true,
      password: '',
      confirmPassword: '',
      pwdLoading: false
    });
  },

  // 关闭弹窗
  closePwdModal() {
    this.setData({ showPwdModal: false });
  },

  onInputPassword(e) {
    this.setData({ password: e.detail.value });
  },
  onInputConfirmPassword(e) {
    this.setData({ confirmPassword: e.detail.value });
  },

  // 保存密码
  async onSavePassword() {
    const { password, confirmPassword } = this.data;
    if (!password || !confirmPassword) {
      wx.showToast({ title: '请输入密码', icon: 'none' }); return;
    }
    if (password !== confirmPassword) {
      wx.showToast({ title: '两次密码不一致', icon: 'none' }); return;
    }
    if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/.test(password)) {
      wx.showToast({ title: '密码需8位且含字母和数字', icon: 'none' }); return;
    }
    this.setData({ pwdLoading: true });
    try {
      const res = await api.request({
        url: '/api/register/set_password',
        method: 'POST',
        data: { password, confirm_password: confirmPassword }
      });
      this.setData({ pwdLoading: false });
      if (res.code === 200) {
        wx.showToast({ title: '密码设置成功', icon: 'success' });
        this.setData({ showPwdModal: false });
      } else {
        wx.showToast({ title: res.msg || '设置失败', icon: 'none' });
      }
    } catch (e) {
      this.setData({ pwdLoading: false });
      wx.showToast({ title: '网络错误', icon: 'none' });
    }
  },

  // 退出登录 - 严格契合后端
  async logout() {
    wx.showModal({
      title: '确认退出',
      content: '确定要退出登录吗？',
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '退出中...' });
            // 调用后端退出登录接口
            const logoutRes = await api.request({
              url: '/api/logout',
              method: 'POST'
            });
            wx.hideLoading();
            // 无论后端返回什么，都清除本地token
            wx.removeStorageSync('access_token');
            wx.removeStorageSync('refresh_token');
            wx.showToast({
              title: '退出成功',
              icon: 'success'
            });
            setTimeout(() => {
              wx.redirectTo({
                url: '/pages/login-1/login-1'
              });
            }, 1000);
          } catch (error) {
            wx.hideLoading();
            wx.removeStorageSync('access_token');
            wx.removeStorageSync('refresh_token');
            wx.showToast({
              title: '退出成功',
              icon: 'success'
            });
            setTimeout(() => {
              wx.redirectTo({
                url: '/pages/login-1/login-1'
              });
            }, 1000);
          }
        }
      }
    });
  }
});